package service

import (
	"encoding/json"
	"fmt"
	"strconv"
	"time"
	"cmsapi/src/model"

	//"service"

	//"fmt"

	//"fmt"
	"cmsapi/src/lib"
	//"net/http"

	"github.com/gin-gonic/gin"
	//"github.com/gomodule/redigo/redis"
	//"database/sql"
	//"time"
	//"gorm.io/driver/mysql"
	//"gorm.io/gorm"
	//"gorm.io/driver/mysql"
	//"gorm.io/gorm"
	//"gorm.io/gorm/logger"
)

//查询一条数据
func One(c *gin.Context) {
	//lib.Check(c)
	//fmt.Println(s)
	where, like := lib.Get(c)

	//fmt.Printf("queyr %s  \r\n", queyr)
	//id := where["id"]
	table := c.Param("action")
	var data [](map[string]interface{})
	//lib.Mysql.Debug().Table(lib.DbInfo.Prefix+table).Where("id = ?", id).Limit(1).Find(&data) //Debug().
	rel := lib.Mysql.Debug().Table(lib.DbInfo.Prefix + table).Where(where)
	for lk, lv := range like {
		rel.Where(lk+" LIKE ?", "%"+lv+"%")
	}

	rel.Limit(1).Find(&data) //Debug().
	c.Set("code", 201)
	//fmt.Println(data, data)
	//	var d map[string]interface{}
	if data != nil {

		atime := (data[0]["add_time"]).(int64)
		fmt.Printf("addtime %s=>%T \r\n", atime, atime)
		datatime := time.Unix(atime, 0).Format("2006-01-02 15:04:05")
		data[0]["add_time"] = datatime
		delete(data[0], "user_id")
		//	delete(data[0], "ip")

		jsondata, _ := json.Marshal(data[0])
		c.Set("jsondata", string(jsondata))
	} else {
		c.Set("jsondata", "{}")
	}

	wheredata, _ := json.Marshal(where)
	c.Set("wheredata", string(wheredata))
	//写入日志
	model.LogCreate(c, lib.Mysql, map[string]interface{}{"type": "one", "method": "get", "token": c.DefaultQuery("token", "")})
	c.Next()

}

//列表类型
func List(c *gin.Context) {
	//	lib.Check1(c)
	where, like := lib.Get(c)
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	if page == 0 {
		page = 1
	}
	pagesize, _ := strconv.Atoi(c.DefaultQuery("pagesize", "1"))
	if pagesize == 0 {
		pagesize = 10
	}
	fmt.Println("page,pagesize", page, pagesize)
	//id := c.Query("id")
	//query := c.Query()
	//fmt.Println(query)
	table := c.Param("action")
	//var data (map[string]string)
	var data [](map[string]interface{})
	//lib.Mysql.Debug().Table(lib.DbInfo.Prefix+table).Where("id >= ?", id).Find(&data) //Debug().
	rel1 := lib.Mysql.Debug().Table(lib.DbInfo.Prefix + table).Where(where)
	rel := lib.Mysql.Debug().Table(lib.DbInfo.Prefix + table).Where(where)
	for lk, lv := range like {
		rel1.Where(lk+" LIKE ?", "%"+lv+"%")
		rel.Where(lk+" LIKE ?", "%"+lv+"%")
	}

	//	c := rel
	var counts model.Counts
	rel1.Select("count(1) as count").Scan(&counts)

	//fmt.Printf("\r\n \r\n \r\n \r\n countcount %s=>%T  \r\n \r\n \r\n ", counts, counts)
	where["count"] = counts.Count
	where["page"] = page
	where["pagesize"] = pagesize
	total := int(counts.Count / pagesize)
	if (pagesize * total) < counts.Count {
		where["total"] = total + 1
	} else {
		where["total"] = total
	}

	rel.Select("*")
	rel.Limit(pagesize).Offset((page - 1) * pagesize).Find(&data) //Debug().

	for k, v := range data {
		//fmt.Printf("\r\n vvvvvvvvvv %s=>%T %s", v, v, k)
		atime := (v["add_time"]).(int64)
		datatime := time.Unix(atime, 0).Format("2006-01-02 15:04:05")
		data[k]["add_time"] = datatime
		delete(data[k], "user_id")
		//	delete(data[k], "ip")
	}

	c.Set("code", 202)

	jsondata, _ := json.Marshal(data)

	c.Set("jsondata", string(jsondata))

	wheredata, _ := json.Marshal(where)
	c.Set("wheredata", string(wheredata))
	model.LogCreate(c, lib.Mysql, map[string]interface{}{"type": "list", "method": "get", "token": c.DefaultQuery("token", "")})
	c.Next()

}

//所有请求
func Request(c *gin.Context) {
	//func Request(c *CodeMessage) {
	//controller := c.Param("controller")

	/*
		controller := c.Param("controller")
		action := c.Param("action")
		query := c.Query()

	*/

	desc := lib.Desc("activity")
	fmt.Printf("%s=>%T ", desc, desc)
	id := c.Query("id")
	//results,err := engine.Where("id=?", 6).Search(&users).Json() //返回查询结果的json字符串

	//engine, err := xorm.NewEngine("mysql", fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8&parseTime=True&loc=Local", "root", "", "127.0.0.1", "3306", "mysql"))
	//if err != nil {
	//	panic(err)
	//}
	//engine.ShowExecTime(true)
	//engine.ShowSQL(true)
	/*
		tpl := xorm.Default("./templates", ".tpl")
		tpl.SetFuncs("test.tpl", xorm.FuncMap{"ShowTimestamp": ShowTimestamp})
		err = engine.RegisterSqlTemplate(tpl)
		if err != nil {
			panic(err)
		}

		result := engine.SqlTemplateClient("test.tpl",&map[string]interface{}{"now":time.Now()}).Query()
	*/
	//var _list interface{}
	//engine.Sql("select * from tx_activity where id >=?", 1).Find(&_list)
	//fmt.Println("xorm _list", _list)

	/*/
	rows, _ := lib.Mysql.Debug().Table(lib.DbInfo.Prefix+"activity").Where("id >= ?", id).Rows()
	//var _list map[string]string
	//var _list map[int]model.ActivityData
	type _s struct {
		Val model.ActivityData
	}
	var _list _s
	fmt.Println("all", rows)
	i := 0
	for rows.Next() {
		fmt.Println("next", *rows)
		lib.Mysql.ScanRows(rows, &(_list["Val"]))
		//	rows.Scan(&_list)

		// 做某事

	}
	fmt.Println("_list", _list)
	*/
	//var data []model.ActivityData
	var data [](map[string]interface{})
	lib.Mysql.Debug().Table(lib.DbInfo.Prefix+"activity").Where("id >= ?", id).Find(&data) //Debug().
	for k, v := range data {
		//fmt.Printf("\r\n vvvvvvvvvv %s=>%T %s", v, v, k)
		atime := (v["add_time"]).(int64)
		datatime := time.Unix(atime, 0).Format("2006-01-02 15:04:05")
		data[k]["add_time"] = datatime
	}
	/*
		//v.(int64)
		atime := (data[0]["add_time"]).(int64)
		fmt.Printf("\r\n sssssss %s=>%T %s", atime, atime)
		data[1]["add_time"] = 123456

		x := time.Unix(atime, 0).Format("2006-01-02 15:04:05")
		fmt.Printf("\r\n\r\n data  %s=>%T %s \r\n", atime, atime, x)
		data[2]["add_time"] = x
	*/
	//fmt.Printf("%s=>%T %s", Strval(data[0]["add_time"]), Strval(data[0]["add_time"]))
	//interface2String(data[0]["add_time"])
	//int64_ := int64(1234)
	//	x := time.Unix(atime, 0).Format("2006-01-02 15:04:05")
	//fmt.Printf("\r\n\r\n data  %s=>%T %s \r\n", atime, atime, x)
	//cm := CodeMessage{"200", "请成求功"} //json.Marshal(CodeMessage{200, "请成求功"})
	//var cm CodeMessage
	//cm.Code = "200"
	///cm.Message = "请求成功"
	c.Set("code", 200)
	//c.Code = "1111"
	jsondata, _ := json.Marshal(data)
	/*
		cm := CodeMessage{"200", "请成求功"}
		fmt.Printf("%s=>%k \r\n", cm, cm)
		fmt.Printf("%s=>%k \r\n", data, data)

		c.Set("cm", cm)
	*/
	c.Set("jsondata", string(jsondata))
	c.Next()

	/*
		//db.Raw("SELECT id, name, age FROM users WHERE name = ?", 3).Scan(&result)
		//fmt.Printf("%s %T", d, d)
		//data := []string{"a", "b"}
		data := gin.H{"a": "b", "c": gin.H{"c2": "cc2", "d2": "dd2", "c3": gin.H{"eee4": "eeeee4"}, "fff": d}}
		dataType, _ := json.Marshal(data)
		jsondata := string(dataType)
		c.Set("jsondata", jsondata)

		c.Set("jsondata", jsondata)


		//jsondata := []string{"a", "bb", "cc", "dd"}
		//jsondata := gin.H{"a": "b", "c": gin.H{"c2": "cc2", "d2": "dd2", "c3": gin.H{"eee4": "eeeee4"}}}

		//var dbInfo lib.DBInfo
		//fmt.Println("lib.DbInfo", lib.DbInfo)

		c.Next()
		//请求后逻辑
		//c.JSON(http.StatusOK, value)
		////	Json(c)
		//}

		//Json(c)

		//	c.JSON(http.StatusOK, controller+" __ "+action+" __ "+id+"|"+s)
		/*
			data := model.ActivityData{}
			id := c.Query("id")
			lib.Mysql.Debug().Table("tx_activity").Where("id = ?", id).First(&data) //Debug().


			_, _ = lib.RedisSet("test1", "abc", 123)
			_, _ = lib.RedisSet("test2", []string{"abcc"}, 123)
			_, _ = lib.RediSSet("test3", []int{1, 2, 3, 4, 5}, 123)

			t := map[string]string{"a": "b"}
			//	fmt.Printf("t4 %s=>%T | %s=>%T   \r\n", t, t, t, t)
			s, _ := lib.RedisSet("test4", t, 123)
			fmt.Println(s)

			_, _ = lib.RedisGet("test1")
			_, _ = lib.RedisGet("test2")
			_, _ = lib.RedisGet("test3")
			v, _ := lib.RedisGet("test4")

			c.JSON(http.StatusOK, data)
	*/
}
